#!/bin/sh

set -e

INITIAL_HEAD=$(git rev-parse HEAD)
printf "HEAD before auto generating docs and target_database = ${INITIAL_HEAD}\n"

printf "Attempting to update the target database snapshot with the latest changes\n"
python ci_scripts/sync_board_database.py -vvv
git add src/mbed_tools/targets/_internal/data/board_database_snapshot.json
git add news/

printf "Adding license headers\n"
pre-commit run licenseheaders --all-files > /dev/null 2>&1 || true

if ! NEW_VERSION=$(python ci_scripts/bump_version.py -vvv -n news/); then
    printf "No news files detected. Exiting.\n"
    exit 0
fi

# Update the index so we can check any recently staged changes
git update-index -q --ignore-submodules --refresh

if ! git diff-index --cached --quiet HEAD --ignore-submodules --
then
    printf "Found staged changes to commit after target database update: $(git diff-index --cached --name-status --ignore-submodules HEAD)\n"
    # Towncrier will fail if it detects a news file that has not been committed to
    # the repository. So we need to ensure the news file generated by
    # sync_board_database.py was committed before running towncrier.
    git commit -m "Prepare mbed-tools release ${NEW_VERSION}"
fi

# Generate changelog from news fragments
towncrier --yes --version "${NEW_VERSION}"
git add ./CHANGELOG.md

LATEST_HEAD=$(git rev-parse HEAD)
if [ "$LATEST_HEAD" = "$INITIAL_HEAD" ]; then
    printf "No updates were made during the release process, committing CHANGELOG\n"
    git commit -m "Prepare mbed-tools release ${NEW_VERSION}"
else
    printf "A commit was made to update the docs and/or target database. Amending the commit to include CHANGELOG\n"
    git commit --amend -C HEAD
fi

printf "Tagging version ${NEW_VERSION}"
git tag "${NEW_VERSION}"

# Push the commit and tag to the remote. Relies on `GIT_TOKEN` environment
# variable being set.
printf "Pushing tag and master branch to remote\n"
git push "https://${GIT_TOKEN}@github.com/ARMmbed/mbed-tools.git" master
git push "https://${GIT_TOKEN}@github.com/ARMmbed/mbed-tools.git" "${NEW_VERSION}"
